package 力扣._7022_限制条件下元素之间的最小绝对差;

import java.util.ArrayList;
import java.util.Comparator;
import java.util.List;

public class Solution2 {
    static class NumandIndex {
        int num;
        int index;

        public NumandIndex(int num, int index) {
            this.num = num;
            this.index = index;
        }
    }

    public int minAbsoluteDifference(List<Integer> nums, int x) {
        int min = Integer.MAX_VALUE;
        List<NumandIndex> list = new ArrayList<>();
        for (int i = 0; i < nums.size(); i++) {
            list.add(new NumandIndex(nums.get(i), i));
        }
        list.sort(Comparator.comparingInt(o -> o.num));

        for (int i = 0; i < list.size(); i++) {
            //向左右两遍找到下标距离大于等于x的值即可
            int l = i - 1, r = i + 1;
            while (l >= 0) {
                if (Math.abs(list.get(l).index - list.get(i).index) >= x)
                    break;
                l--;
            }
            while (r < list.size()) {
                if (Math.abs(list.get(r).index - list.get(i).index) >= x)
                    break;
                r++;
            }
            if (l >= 0)
                min = Math.min(min, Math.abs(list.get(l).num - list.get(i).num));
            if (r < list.size())
                min = Math.min(min, Math.abs(list.get(r).num - list.get(i).num));
            if (min == 0)
                break;

        }
        return min;
    }
}
